package com.shensi.appCollect.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.shensi.appCollect.enums.BatchTaskStatus;
import com.shensi.appCollect.pojo.BatchSubtask;
import com.shensi.appCollect.pojo.dto.SendWxTemplateMessageRunnableParam;
import com.shensi.appCollect.pojo.wx.WxTemplateMessageSendRequest;
import com.shensi.appCollect.service.BatchSubtaskService;
import com.shensi.appCollect.utils.JsonUtils;
import com.shensi.appCollect.utils.MyLambadaUpdateWrapper;
import com.shensi.appCollect.utils.weixinapp.WxPushUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Collections;

/**
 * @date 2023/11/21
 */
public class SendWxTemplateMessageSubtaskRunnable implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(SendWxTemplateMessageSubtaskRunnable.class);
    private final BatchTaskExecutor batchTaskExecutor;
    private final BatchSubtaskService batchSubtaskService;
    private WxPushUtil wxPushUtil;
    private SendWxTemplateMessageRunnableParam param;
    private BatchSubtask subtask;

    public SendWxTemplateMessageSubtaskRunnable(WxPushUtil wxPushUtil,
                                                BatchTaskExecutor batchTaskExecutor,
                                                BatchSubtaskService batchSubtaskService,
                                                SendWxTemplateMessageRunnableParam param,
                                                BatchSubtask subtask) {
        this.wxPushUtil = wxPushUtil;
        this.batchTaskExecutor = batchTaskExecutor;
        this.batchSubtaskService = batchSubtaskService;
        this.param = param;
        this.subtask = subtask;
    }

    @Override
    public void run() {
        log.info("开始处理数据,subtaskId:[{}],index:[{}]",subtask.getId(),param.getIndex());
        int i = doRun();
        log.info("处理数据结束,subtaskId:[{}],index:[{}],res:[{}]",subtask.getId(),param.getIndex(),i);
        MyLambadaUpdateWrapper<BatchSubtask> updateWrapper = new MyLambadaUpdateWrapper<>();
        boolean finished;
        synchronized (subtask){
            if (i>0) {
                updateWrapper.incrementSet(BatchSubtask::getSuccessNum,1);
                subtask.setSuccessNum(subtask.getSuccessNum()+1);
            }else{
                updateWrapper.incrementSet(BatchSubtask::getFailNum,1);
                subtask.setFailNum(subtask.getFailNum()+1);
            }
            finished = subtask.getItemNum() <= (subtask.getSuccessNum()+ subtask.getFailNum()+subtask.getSkipNum());
        }
        if (finished) {
            updateWrapper.set(BatchSubtask::getSubtaskStatus,BatchTaskStatus.SUCCESS)
                    .set(BatchSubtask::getCompleteTime,LocalDateTime.now());
        }
        updateWrapper.eq(BatchSubtask::getId,subtask.getId());
        batchSubtaskService.update(updateWrapper);
        if(finished){
            log.info("子任务完成,更新状态,subtaskId:[{}]",subtask.getId());
            batchTaskExecutor.runEarlySubtask();
        }
    }

    private int doRun(){
        WxTemplateMessageSendRequest sendRequest = param.getSendRequest();
        try {
            String jsonStr = JsonUtils.objectToJson(sendRequest);
            log.info("消息推送请求参数:{}", jsonStr);
            String body = wxPushUtil.sendWxTemplateMsg(param.getGzhAppId(), param.getGzhAppSecret(), jsonStr);
            if (body != null) {
                log.info("消息推送结果,{}",body);
                return 1;
            }else{
                log.error("消息推送失败,body为空");
                return 0;
            }
        } catch (JsonProcessingException e) {
            log.error("消息推送失败");
            log.error(e.getMessage(),e);
        }
        return 0;
    }
}
